<template>
  <div class="control-center">
    <!-- 粒子动画背景 -->
    <div id="particles-js"></div>
    
    <!-- 修改数据概览卡片部分 -->
  <div class="overview-cards">
    <div class="card">
      <div class="card-content">
        <i class="fas fa-server"></i>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.apis || 0 }}</div>
          <div class="stat-label">平台接口</div>
        </div>
        <div class="stat-trend up">
          <i class="fas fa-arrow-up"></i>
          100%
        </div>
      </div>
      <div class="progress-bar">
        <div class="progress" style="width: 100%"></div>
      </div>
    </div>

    <div class="card">
      <div class="card-content">
        <i class="fas fa-users"></i>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.developers || 0 }}</div>
          <div class="stat-label">开发者</div>
        </div>
        <div class="stat-trend up">
          <i class="fas fa-arrow-up"></i>
          100%
        </div>
      </div>
      <div class="progress-bar">
        <div class="progress" style="width: 100%"></div>
      </div>
    </div>
    <div class="card">
      <div class="card-content">
        <i class="fas fa-code"></i>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.totalCalls || 0 }}</div>
          <div class="stat-label">调用次数</div>
        </div>
        <div class="stat-trend up">
          <i class="fas fa-arrow-up"></i>
          100%
        </div>
      </div>
      <div class="progress-bar">
        <div class="progress" style="width: 100%"></div>
      </div>
    </div>

    <div class="card">
      <div class="card-content">
        <i class="fas fa-chart-line"></i>
        <div class="stat-info">
          <div class="stat-value">{{ statistics.availability || 0 }}%</div>
          <div class="stat-label">服务可用率</div>
        </div>
        <div class="stat-trend stable">
          <i class="fas fa-equals"></i>
          {{ statistics.availability || 0 }}%
        </div>
      </div>
      <div class="progress-bar">
        <div class="progress" :style="{ width: statistics.availability + '%' }"></div>
      </div>
    </div>
  </div>
    <!-- 实时监控面板 -->
    <div class="monitor-panel">
      <div class="panel-header">
        <h2>系统实时监控</h2>
        <div class="time-selector">
          <button 
            v-for="period in timePeriods" 
            :key="period"
            :class="['time-btn', { active: currentPeriod === period }]"
            @click="currentPeriod = period"
          >
            {{ period }}
          </button>
        </div>
      </div>
      
      <div class="monitor-grid">
        <div class="monitor-card cpu">
          <h3>CPU使用率</h3>
          <div class="gauge-chart">
            <div class="gauge-value">{{ getCpuUsage }}%</div>
            <div class="gauge-circle">
              <svg viewBox="0 0 100 100">
                <circle
                  cx="50"
                  cy="50"
                  r="45"
                  fill="none"
                  stroke="#eee"
                  stroke-width="8"
                />
                <circle
                  cx="50"
                  cy="50"
                  r="45"
                  fill="none"
                  stroke="#1a237e"
                  stroke-width="8"
                  stroke-linecap="round"
                  :stroke-dasharray="circumference"
                  :stroke-dashoffset="dashOffset"
                  transform="rotate(-90 50 50)"
                />
              </svg>
            </div>
          </div>
          <div class="cpu-details">
            <p>核心数：{{ getCpuCoreCount }}</p>
            <p>型号：{{ getCpuModel }}</p>
            <p v-if="getCpuTemperature">温度：{{ getCpuTemperature }}°C</p>
          </div>
        </div>

        <div class="monitor-card memory">
          <h3>内存占用</h3>
          <div class="memory-usage">
            <div class="usage-bar">
              <div class="used" :style="{ width: getMemoryUsage + '%' }"></div>
            </div>
            <div class="memory-stats">
              <span>已用: {{ formatMemory(getMemoryUsed) }}</span>
              <span>总计: {{ formatMemory(getMemoryTotal) }}</span>
            </div>
            <div class="memory-usage-text">
              使用率: {{ getMemoryUsage }}%
            </div>
          </div>
        </div>

        <div class="monitor-card network">
          <h3>网络流量</h3>
          <div class="network-stats">
            <div class="stat-item">
              <i class="fas fa-arrow-up"></i>
              <span>上行: {{ formatSpeed(getNetworkUploadSpeed) }}</span>
            </div>
            <div class="stat-item">
              <i class="fas fa-arrow-down"></i>
              <span>下行: {{ formatSpeed(getNetworkDownloadSpeed) }}</span>
            </div>
            <div class="total-transfer">
              <div>总上传: {{ formatBytes(getNetworkTotalUpload) }}</div>
              <div>总下载: {{ formatBytes(getNetworkTotalDownload) }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 最近活动日志 -->
    <div class="activity-log">
      <h2>系统活动日志</h2>
      <div class="log-list">
        <div 
          v-for="(log, index) in activityLogs" 
          :key="index"
          class="log-item"
          :class="log.type"
        >
          <div class="log-icon">
            <i :class="getLogIcon(log.type)"></i>
          </div>
          <div class="log-content">
            <div class="log-message">{{ log.message }}</div>
            <div class="log-time">{{ log.time }}</div>
          </div>
          <div class="log-status" :class="log.status">
            {{ log.status }}
          </div>
        </div>
      </div>
    </div>

    <!-- 快速操作面板 -->
    <div class="quick-actions">
      <h2>快速操作</h2>
      <div class="action-grid">
        <button 
          v-for="action in quickActions" 
          :key="action.id"
          class="action-btn"
          @click="handleQuickAction(action.id)"
        >
          <i :class="action.icon"></i>
          <span>{{ action.label }}</span>
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'ControlCenter',
  data() {
    return {
      // 统计数据
      statistics: [
        {
          icon: 'fas fa-server',
          value: '1,884',
          label: '平台接口',
          trend: 'up',
          percentage: 85
        },
        {
          icon: 'fas fa-users',
          value: '1,667',
          label: '开发者',
          trend: 'up',
          percentage: 92
        },
        {
          icon: 'fas fa-code',
          value: '5,522',
          label: '调用次数',
          trend: 'up',
          percentage: 78
        },
        {
          icon: 'fas fa-chart-line',
          value: '99.9%',
          label: '服务可用率',
          trend: 'stable',
          percentage: 99.9
        }
      ],
      statistics: {
        totalCalls: 0,
        successCalls: 0,
        availability: 0,
        developers: 0,
        apis: 0
      },
      apiKinds: 0,

      // 时间周期选择
      timePeriods: ['实时', '1小时', '24小时', '7天'],
      currentPeriod: '实时',

      // 系统监控数据
      systemInfo: {
        cpu: {},
        memory: {},
        network: {}
      },

      // 活动日志
      activityLogs: [
        {
          type: 'info',
          message: '新用户注册',
          time: '2分钟前',
          status: 'success'
        },
        {
          type: 'warning',
          message: 'API调用次数超过阈值',
          time: '5分钟前',
          status: 'warning'
        },
        {
          type: 'error',
          message: '服务器负载过高',
          time: '10分钟前',
          status: 'error'
        }
      ],

      // 快速操作
      quickActions: [
        {
          id: 'add-api',
          icon: 'fas fa-plus',
          label: '添加接口'
        },
        {
          id: 'system-status',
          icon: 'fas fa-server',
          label: '系统状态'
        },
        {
          id: 'user-manage',
          icon: 'fas fa-users-cog',
          label: '用户管理'
        },
        {
          id: 'settings',
          icon: 'fas fa-cog',
          label: '系统设置'
        }
      ],

      timer: null,
      circumference: 2 * Math.PI * 45,
      isLoading: false  // 添加请求锁
    }
  },
  computed: {
    // CPU相关计算属性
    getCpuUsage() {
      return this.systemInfo.cpu && this.systemInfo.cpu.usage ? 
        this.systemInfo.cpu.usage.toFixed(1) : 0
    },
    getCpuCoreCount() {
      return this.systemInfo.cpu && this.systemInfo.cpu.coreCount || 0
    },
    getCpuModel() {
      return this.systemInfo.cpu && this.systemInfo.cpu.model || 'Unknown'
    },
    getCpuTemperature() {
      return this.systemInfo.cpu && this.systemInfo.cpu.temperature || 0
    },
    
    // 内存相关计算属性
    getMemoryUsage() {
      return this.systemInfo.memory && this.systemInfo.memory.usage ? 
        this.systemInfo.memory.usage.toFixed(1) : 0
    },
    getMemoryUsed() {
      return this.systemInfo.memory && this.systemInfo.memory.used || 0
    },
    getMemoryTotal() {
      return this.systemInfo.memory && this.systemInfo.memory.total || 0
    },
    
    // 网络相关计算属性
    getNetworkUploadSpeed() {
      return this.systemInfo.network && this.systemInfo.network.uploadSpeed || 0
    },
    getNetworkDownloadSpeed() {
      return this.systemInfo.network && this.systemInfo.network.downloadSpeed || 0
    },
    getNetworkTotalUpload() {
      return this.systemInfo.network && this.systemInfo.network.totalUpload || 0
    },
    getNetworkTotalDownload() {
      return this.systemInfo.network && this.systemInfo.network.totalDownload || 0
    },
    
    dashOffset() {
      return this.circumference * (1 - (this.getCpuUsage / 100))
    }
  },
  methods: {
    formatMemory(bytes) {
      if (!bytes) return '0 GB'
      return (bytes / 1024 / 1024 / 1024).toFixed(2) + ' GB'
    },
    
    formatSpeed(speed) {
      if (!speed) return '0 MB/s'
      return speed.toFixed(2) + ' MB/s'
    },
    
    formatBytes(bytes) {
      if (!bytes) return '0 B'
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
      const i = Math.floor(Math.log(Math.max(bytes, 1)) / Math.log(1024))
      return (bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i]
    },
    
    // 获取统计数据
    async fetchStatistics() {
      try {
        const response = await axios.get('/api/admin/preData/getApiStatistics')
        console.log(response.data)
        const result = response.data
        if (result.code === 200) {
          const data = result.data[0]
          this.statistics = {
            totalCalls: data.totalCalls,
            successCalls: data.successCalls,
            availability: data.availability,
            developers: data.developers,
            apis: data.apis
          }
          this.apiKinds = result.apiKinds || 0
        }
      } catch (error) {
        console.error('获取统计数据失败:', error)
      }
    },
    getTrendIcon(trend) {
      return {
        up: 'fas fa-arrow-up',
        down: 'fas fa-arrow-down',
        stable: 'fas fa-equals'
      }[trend]
    },
    getLogIcon(type) {
      return {
        info: 'fas fa-info-circle',
        warning: 'fas fa-exclamation-triangle',
        error: 'fas fa-times-circle'
      }[type]
    },
    handleQuickAction(actionId) {
      // 处理快速操作点击
      console.log('Quick action clicked:', actionId)
    },
    async fetchSystemInfo() {
      if (this.isLoading) {
        return
      }
      
      try {
        this.isLoading = true
        const response = await fetch('/api/monitor')
        const result = await response.json()
        if (result.code === 200) {
          this.systemInfo = result.data
        } else {
          console.error('获取系统信息失败:', result.message)
        }
      } catch (error) {
        console.error('获取系统信息失败:', error)
      } finally {
        this.isLoading = false
      }
    },
    startMonitoring() {
      this.fetchSystemInfo() // 立即获取一次数据
      this.timer = setInterval(() => {
        this.fetchSystemInfo()
      }, 2000)
    },
    stopMonitoring() {
      if (this.timer) {
        clearInterval(this.timer)
        this.timer = null
      }
    }
  },
  mounted() {
    // 初始化粒子效果
    //this.initParticles()
    this.fetchStatistics() // 组件挂载时获取数据
    this.startMonitoring()
  },
 
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  }

}
</script>

<style scoped>
.control-center {
  padding: 24px;
  min-height: 100vh;
  background-color: var(--bg-secondary);
  color: var(--text-primary);
  position: relative;
}

/* 粒子背景 */
#particles-js {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

/* 数据概览卡片 */
.overview-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
  position: relative;
  z-index: 1;
}

.card {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.card-content {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.card i {
  font-size: 24px;
  color: #1a237e;
  margin-right: 15px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #1a237e;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.stat-trend {
  padding: 4px 8px;
  border-radius: 20px;
  font-size: 12px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.stat-trend.up {
  background: rgba(76, 175, 80, 0.1);
  color: #4caf50;
}

.stat-trend.down {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.stat-trend.stable {
  background: rgba(33, 150, 243, 0.1);
  color: #2196f3;
}

.progress-bar {
  height: 4px;
  background: #eee;
  border-radius: 2px;
  overflow: hidden;
}

.progress {
  height: 100%;
  background: linear-gradient(90deg, #1a237e, #3949ab);
  transition: width 0.3s ease;
}

/* 监控面板 */
.monitor-panel {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.time-selector {
  display: flex;
  gap: 10px;
}

.time-btn {
  padding: 6px 12px;
  border: none;
  background: none;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.time-btn.active {
  background: #1a237e;
  color: white;
}

.monitor-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.monitor-card {
  padding: 20px;
  border-radius: 8px;
  background: #f8f9fa;
}

/* CPU使用率图表 */
.gauge-chart {
  position: relative;
  width: 150px;
  height: 150px;
  margin: 20px auto;
}

.gauge-value {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  font-weight: bold;
  color: #1a237e;
}

.gauge-circle {
  width: 100%;
  height: 100%;
}

.gauge-circle svg {
  width: 100%;
  height: 100%;
  transform: rotate(0deg);
}

.gauge-circle circle {
  transition: stroke-dashoffset 0.3s ease;
}

/* 内存使用图表 */
.memory-usage {
  margin-top: 20px;
}

.usage-bar {
  height: 20px;
  background: #eee;
  border-radius: 10px;
  overflow: hidden;
  margin-bottom: 10px;
}

.used {
  height: 100%;
  background: linear-gradient(90deg, #1a237e, #3949ab);
  transition: width 0.3s ease;
}

.memory-stats {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

/* 网络流量 */
.network-stats {
  margin-top: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.stat-item i {
  color: #1a237e;
}

/* 活动日志 */
.activity-log {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.log-list {
  margin-top: 20px;
}

.log-item {
  display: flex;
  align-items: center;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 10px;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.log-item:hover {
  background: #f0f0f0;
}

.log-icon {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
}

.log-item.info .log-icon {
  background: rgba(33, 150, 243, 0.1);
  color: #2196f3;
}

.log-item.warning .log-icon {
  background: rgba(255, 152, 0, 0.1);
  color: #ff9800;
}

.log-item.error .log-icon {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

.log-content {
  flex: 1;
}

.log-message {
  font-weight: 500;
}

.log-time {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.log-status {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
}

.log-status.success {
  background: rgba(76, 175, 80, 0.1);
  color: #4caf50;
}

.log-status.warning {
  background: rgba(255, 152, 0, 0.1);
  color: #ff9800;
}

.log-status.error {
  background: rgba(244, 67, 54, 0.1);
  color: #f44336;
}

/* 快速操作 */
.quick-actions {
  background-color: var(--card-bg);
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.action-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 15px;
  margin-top: 20px;
}

.action-btn {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  padding: 20px;
  border: none;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.action-btn:hover {
  background: #1a237e;
  color: white;
  transform: translateY(-2px);
}

.action-btn i {
  font-size: 24px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .control-center {
    padding: 16px;
  }
  
  .overview-cards {
    grid-template-columns: 1fr;
  }
  
  .monitor-grid {
    grid-template-columns: 1fr;
  }
  
  .action-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 暗色主题支持 */
@media (prefers-color-scheme: dark) {
  .control-center {
    background: #121212;
  }
  
  .card,
  .monitor-panel,
  .activity-log,
  .quick-actions {
    background: #1e1e1e;
    color: #fff;
  }
  
  .monitor-card {
    background: #2d2d2d;
  }
  
  .action-btn {
    background: #2d2d2d;
    color: #fff;
  }
  
  .log-item {
    background: #2d2d2d;
  }
  
  .stat-label,
  .log-time {
    color: #aaa;
  }
}
</style>
